package com.ajieee.merge.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.ajieee.merge.entity.sys.dto.LoginInfoDTO;
import com.ajieee.merge.entity.sys.po.UserPO;
import com.ajieee.merge.entity.sys.vo.TokenVO;
import com.ajieee.merge.enums.common.DeleteFlag;
import com.ajieee.merge.event.LoginSuccessEvent;
import com.ajieee.merge.exception.AuthException;
import com.ajieee.merge.mapper.UserMapper;
import com.ajieee.merge.service.AuthService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

/**
 * @author ajieee
 * @date 2025-10-25
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {

	private final UserMapper userMapper;

	private final ApplicationEventPublisher eventPublisher;

	@Override
	public TokenVO login(LoginInfoDTO loginInfoDTO) {
		String username = loginInfoDTO.getUsername();
		UserPO userPO = userMapper.selectOne(Wrappers.<UserPO>lambdaQuery()
				.eq(UserPO::getUsername, username)
				.eq(UserPO::getDeleteFlag, DeleteFlag.NORMAL));
		if (userPO == null) {
			throw new AuthException(username, "用户不存在");
		}
		if (!passwordCheck(loginInfoDTO.getPassword(), userPO.getPassword())) {
			throw new AuthException(username, "密码错误");
		}

		StpUtil.login(userPO.getUsername());
		String tokenValue = StpUtil.getTokenInfo().getTokenValue();
		eventPublisher.publishEvent(new LoginSuccessEvent(userPO, tokenValue));

		return new TokenVO(tokenValue);
	}

	private boolean passwordCheck(String rawPwd, String encodePwd) {
		return SaSecureUtil.md5(rawPwd).equals(encodePwd);
	}

}

